﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Automation;

namespace CalcUIA
{
    internal class ClickEvent
    {
        
        const int MouseeventfLeftdown = 0x0002;
        const int MouseeventfLeftup = 0x0004;
               
        /// <summary>
        /// Add mouse move event
        /// </summary>
        /// <param name="x">Move to specify x coordinate</param>
        /// <param name="y">Move to specify y coordinate</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        extern static bool SetCursorPos(int x, int y);
        /// <summary>
        /// Mouse click event
        /// </summary>
        /// <param name="mouseEventFlag">MouseEventFlag </param>
        /// <param name="incrementX">X coordinate</param>
        /// <param name="incrementY">Y coordinate</param>
        /// <param name="data"></param>
        /// <param name="extraInfo"></param>
        [DllImport("user32.dll")]
        extern static void mouse_event(int mouseEventFlag, int incrementX, int incrementY, uint data, UIntPtr extraInfo);

        public static void ClickLeftMouse(AutomationElement element, int X, int Y)
        {
            if (element == null)
            {
                throw new NullReferenceException(string.Format("Element with AutomationId '{0}' and Name '{1}' can not be find.",
                    element.Current.AutomationId, element.Current.Name));
            }

            var rect = element.Current.BoundingRectangle;
            var incrementX = (int)(rect.Left + X);
            var incrementY = (int)(rect.Top +  Y);

            //Make the cursor position to the element.
            SetCursorPos(incrementX, incrementY);
            //Make the left mouse down and up.
            mouse_event(MouseeventfLeftdown, incrementX, incrementY, 0, (UIntPtr)0);
            mouse_event(MouseeventfLeftup, incrementX, incrementY, 0, (UIntPtr)0);
        }
    }
}